<template>
  <div class="model-weight-category-chart">
    <div class="chart-row">
      <!-- 左侧：模型权重分布 -->
      <div class="chart-section">
        <div class="chart-header">
          <h4>
            <Icon type="ios-pie" size="18" />
            集成模型权重分布
          </h4>
        </div>
        <div class="chart-container">
          <div ref="modelWeightChart" class="chart-content"></div>
          <div class="weight-stats">
            <div class="stat-item" v-for="weight in modelWeights" :key="weight.model">
              <span class="model-label" :class="weight.model">{{ weight.label }}</span>
              <span class="weight-value">{{ (weight.value * 100).toFixed(1) }}%</span>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 右侧：特征类别重要性分布 -->
      <div class="chart-section">
        <div class="chart-header">
          <h4>
            <Icon type="ios-analytics" size="18" />
            特征类别重要性分布
          </h4>
          <div class="model-toggle">
            <Button 
              :type="selectedModel === 'lightgbm' ? 'primary' : 'default'"
              @click="selectedModel = 'lightgbm'"
              size="small"
            >
              LightGBM
            </Button>
            <Button 
              :type="selectedModel === 'xgboost' ? 'primary' : 'default'"
              @click="selectedModel = 'xgboost'"
              size="small"
            >
              XGBoost
            </Button>
          </div>
        </div>
        <div class="chart-container">
          <div ref="categoryChart" class="chart-content"></div>
          <div class="category-details">
            <div class="detail-item" v-for="category in categoryStats" :key="category.name">
              <div class="category-info">
                <span class="category-color" :style="{ background: category.color }"></span>
                <span class="category-name">{{ category.label }}</span>
              </div>
              <div class="category-metrics">
                <span class="category-percentage">{{ category.percentage }}%</span>
                <span class="category-count">{{ category.count }}个特征</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 底部：时间序列重要性热力图 -->
    <div class="heatmap-section">
      <div class="chart-header">
        <h4>
          <Icon type="ios-calendar" size="18" />
          历史负荷时间点重要性热力图 ({{ selectedModel.toUpperCase() }})
        </h4>
      </div>
      <div class="heatmap-container">
        <div ref="heatmapChart" class="heatmap-content"></div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'ModelWeightAndCategoryChart',
  props: {
    featureData: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      selectedModel: 'lightgbm',
      modelWeights: [],
      categoryStats: []
    }
  },
  mounted() {
    this.initCharts()
  },
  watch: {
    featureData: {
      handler() {
        this.updateCharts()
      },
      deep: true
    },
    selectedModel() {
      this.updateCategoryChart()
      this.updateHeatmap()
    }
  },
  methods: {
    initCharts() {
      this.$nextTick(() => {
        this.updateCharts()
      })
    },
    
    updateCharts() {
      this.processModelWeights()
      this.updateModelWeightChart()
      this.updateCategoryChart()
      this.updateHeatmap()
    },
    
    processModelWeights() {
      // 提取集成模型权重
      const ensembleData = this.featureData.filter(item => item.model === 'ensemble')
      const lightgbmWeight = ensembleData.find(item => item.feat === 'weight_lightgbm')
      const xgboostWeight = ensembleData.find(item => item.feat === 'weight_xgboost')
      
      this.modelWeights = [
        {
          model: 'lightgbm',
          label: 'LightGBM',
          value: lightgbmWeight ? lightgbmWeight.imp : 0.5,
          color: '#4ecdc4'
        },
        {
          model: 'xgboost',
          label: 'XGBoost',
          value: xgboostWeight ? xgboostWeight.imp : 0.5,
          color: '#ffd93d'
        }
      ]
    },
    
    updateModelWeightChart() {
      const container = this.$refs.modelWeightChart
      if (!container || this.modelWeights.length === 0) return
      
      container.innerHTML = ''
      
      const size = 180
      const center = size / 2
      const radius = 70
      
      const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg')
      svg.setAttribute('width', size)
      svg.setAttribute('height', size)
      
      let currentAngle = 0
      
      this.modelWeights.forEach(weight => {
        const angle = weight.value * 2 * Math.PI
        const x1 = center + radius * Math.cos(currentAngle)
        const y1 = center + radius * Math.sin(currentAngle)
        const x2 = center + radius * Math.cos(currentAngle + angle)
        const y2 = center + radius * Math.sin(currentAngle + angle)
        
        const largeArc = angle > Math.PI ? 1 : 0
        
        const path = document.createElementNS('http://www.w3.org/2000/svg', 'path')
        path.setAttribute('d', `
          M ${center} ${center}
          L ${x1} ${y1}
          A ${radius} ${radius} 0 ${largeArc} 1 ${x2} ${y2}
          Z
        `)
        path.setAttribute('fill', weight.color)
        path.setAttribute('opacity', '0.8')
        svg.appendChild(path)
        
        // 添加标签
        const labelAngle = currentAngle + angle / 2
        const labelRadius = radius * 0.7
        const labelX = center + labelRadius * Math.cos(labelAngle)
        const labelY = center + labelRadius * Math.sin(labelAngle)
        
        const text = document.createElementNS('http://www.w3.org/2000/svg', 'text')
        text.setAttribute('x', labelX)
        text.setAttribute('y', labelY + 3)
        text.setAttribute('text-anchor', 'middle')
        text.setAttribute('fill', '#fff')
        text.setAttribute('font-size', '12')
        text.setAttribute('font-weight', 'bold')
        text.textContent = `${(weight.value * 100).toFixed(1)}%`
        svg.appendChild(text)
        
        currentAngle += angle
      })
      
      container.appendChild(svg)
    },
    
    updateCategoryChart() {
      // 处理当前选中模型的数据
      const modelData = this.featureData.filter(item => item.model === this.selectedModel)
      
      // 按类别分组统计
      const categories = {
        historical: { name: 'historical', label: '历史负荷', features: [], color: '#4ecdc4' },
        weather: { name: 'weather', label: '气象特征', features: [], color: '#ffd93d' },
        time: { name: 'time', label: '时间特征', features: [], color: '#ff6b6b' }
      }
      
      modelData.forEach(item => {
        if (item.feat.startsWith('hist_load_')) {
          categories.historical.features.push(item)
        } else if (item.feat.startsWith('weather_')) {
          categories.weather.features.push(item)
        } else if (item.feat.startsWith('time_')) {
          categories.time.features.push(item)
        }
      })
      
      // 计算总重要性
      const totalImportance = modelData.reduce((sum, item) => sum + item.imp, 0)
      
      // 生成统计数据
      this.categoryStats = Object.values(categories).map(cat => {
        const totalCatImportance = cat.features.reduce((sum, item) => sum + item.imp, 0)
        return {
          ...cat,
          count: cat.features.length,
          totalImportance: totalCatImportance,
          percentage: totalImportance > 0 ? (totalCatImportance / totalImportance * 100).toFixed(1) : 0
        }
      }).filter(cat => cat.count > 0)
      
      // 渲染饼图
      this.renderCategoryPieChart()
    },
    
    renderCategoryPieChart() {
      const container = this.$refs.categoryChart
      if (!container || this.categoryStats.length === 0) return
      
      container.innerHTML = ''
      
      const size = 180
      const center = size / 2
      const radius = 70
      
      const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg')
      svg.setAttribute('width', size)
      svg.setAttribute('height', size)
      
      const total = this.categoryStats.reduce((sum, cat) => sum + cat.totalImportance, 0)
      let currentAngle = 0
      
      this.categoryStats.forEach(cat => {
        if (cat.totalImportance > 0) {
          const angle = (cat.totalImportance / total) * 2 * Math.PI
          const x1 = center + radius * Math.cos(currentAngle)
          const y1 = center + radius * Math.sin(currentAngle)
          const x2 = center + radius * Math.cos(currentAngle + angle)
          const y2 = center + radius * Math.sin(currentAngle + angle)
          
          const largeArc = angle > Math.PI ? 1 : 0
          
          const path = document.createElementNS('http://www.w3.org/2000/svg', 'path')
          path.setAttribute('d', `
            M ${center} ${center}
            L ${x1} ${y1}
            A ${radius} ${radius} 0 ${largeArc} 1 ${x2} ${y2}
            Z
          `)
          path.setAttribute('fill', cat.color)
          path.setAttribute('opacity', '0.8')
          svg.appendChild(path)
          
          currentAngle += angle
        }
      })
      
      container.appendChild(svg)
    },
    
    updateHeatmap() {
      // 生成历史负荷时间点热力图
      const container = this.$refs.heatmapChart
      if (!container) return
      
      container.innerHTML = ''
      
      // 获取历史负荷数据
      const modelData = this.featureData.filter(item => 
        item.model === this.selectedModel && item.feat.startsWith('hist_load_day')
      )
      
      if (modelData.length === 0) return
      
      // 解析数据结构：day1_t1 到 day7_t96
      const heatmapData = Array(7).fill().map(() => Array(96).fill(0))
      
      modelData.forEach(item => {
        const match = item.feat.match(/day(\d+)_t(\d+)/)
        if (match) {
          const day = parseInt(match[1]) - 1
          const timePoint = parseInt(match[2]) - 1
          if (day >= 0 && day < 7 && timePoint >= 0 && timePoint < 96) {
            heatmapData[day][timePoint] = item.imp
          }
        }
      })
      
      // 找到最大值用于归一化
      const maxValue = Math.max(...modelData.map(item => item.imp))
      
      // 创建热力图
      const width = container.clientWidth || 800
      const height = 200
      const cellWidth = width / 96
      const cellHeight = height / 7
      
      const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg')
      svg.setAttribute('width', width)
      svg.setAttribute('height', height)
      svg.style.background = 'rgba(7, 19, 50, 0.4)'
      svg.style.borderRadius = '8px'
      
      // 绘制热力图单元格
      for (let day = 0; day < 7; day++) {
        for (let timePoint = 0; timePoint < 96; timePoint++) {
          const value = heatmapData[day][timePoint]
          const intensity = maxValue > 0 ? value / maxValue : 0
          
          const rect = document.createElementNS('http://www.w3.org/2000/svg', 'rect')
          rect.setAttribute('x', timePoint * cellWidth)
          rect.setAttribute('y', day * cellHeight)
          rect.setAttribute('width', cellWidth - 1)
          rect.setAttribute('height', cellHeight - 1)
          
          // 根据重要性设置颜色
          if (intensity > 0) {
            const color = this.selectedModel === 'lightgbm' ? 
              `rgba(78, 205, 196, ${0.2 + intensity * 0.8})` : 
              `rgba(255, 217, 61, ${0.2 + intensity * 0.8})`
            rect.setAttribute('fill', color)
          } else {
            rect.setAttribute('fill', 'rgba(255,255,255,0.05)')
          }
          
          rect.setAttribute('stroke', 'rgba(255,255,255,0.1)')
          rect.setAttribute('stroke-width', '0.5')
          
          // 添加工具提示信息
          const title = document.createElementNS('http://www.w3.org/2000/svg', 'title')
          title.textContent = `第${day + 1}天 第${timePoint + 1}个时间点\n重要性: ${value.toFixed(3)}`
          rect.appendChild(title)
          
          svg.appendChild(rect)
        }
      }
      
      // 添加坐标轴标签
      // Y轴标签（天数）
      for (let day = 0; day < 7; day++) {
        const text = document.createElementNS('http://www.w3.org/2000/svg', 'text')
        text.setAttribute('x', -5)
        text.setAttribute('y', day * cellHeight + cellHeight / 2 + 3)
        text.setAttribute('text-anchor', 'end')
        text.setAttribute('fill', '#999')
        text.setAttribute('font-size', '10')
        text.textContent = `第${day + 1}天`
        svg.appendChild(text)
      }
      
      // X轴标签（时间点，每24个标记一次）
      for (let i = 0; i < 96; i += 24) {
        const text = document.createElementNS('http://www.w3.org/2000/svg', 'text')
        text.setAttribute('x', i * cellWidth + cellWidth * 12)
        text.setAttribute('y', height + 15)
        text.setAttribute('text-anchor', 'middle')
        text.setAttribute('fill', '#999')
        text.setAttribute('font-size', '10')
        text.textContent = `${Math.floor(i / 4)}:00`
        svg.appendChild(text)
      }
      
      container.appendChild(svg)
    }
  }
}
</script>

<style lang="less" scoped>
.model-weight-category-chart {
  .chart-row {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 20px;
    margin-bottom: 20px;
  }
  
  .chart-section {
    background: rgba(7, 19, 50, 0.4);
    border: 1px solid #1a3c58;
    border-radius: 8px;
    padding: 20px;
    
    .chart-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 15px;
      
      h4 {
        color: #75deef;
        font-size: 16px;
        margin: 0;
        display: flex;
        align-items: center;
        gap: 8px;
      }
      
      .model-toggle {
        display: flex;
        gap: 5px;
      }
    }
    
    .chart-container {
      display: flex;
      flex-direction: column;
      align-items: center;
      
      .chart-content {
        margin-bottom: 15px;
      }
    }
    
    .weight-stats, .category-details {
      width: 100%;
      
      .stat-item, .detail-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 8px 12px;
        margin-bottom: 5px;
        background: rgba(7, 19, 50, 0.3);
        border-radius: 6px;
        
        .model-label {
          color: #999;
          font-size: 14px;
          
          &.lightgbm {
            color: #4ecdc4;
          }
          
          &.xgboost {
            color: #ffd93d;
          }
        }
        
        .weight-value {
          color: #75deef;
          font-weight: bold;
          font-size: 14px;
        }
        
        .category-info {
          display: flex;
          align-items: center;
          gap: 8px;
          
          .category-color {
            width: 12px;
            height: 12px;
            border-radius: 2px;
          }
          
          .category-name {
            color: #999;
            font-size: 14px;
          }
        }
        
        .category-metrics {
          display: flex;
          flex-direction: column;
          align-items: flex-end;
          
          .category-percentage {
            color: #75deef;
            font-weight: bold;
            font-size: 14px;
          }
          
          .category-count {
            color: #666;
            font-size: 12px;
          }
        }
      }
    }
  }
  
  .heatmap-section {
    background: rgba(7, 19, 50, 0.4);
    border: 1px solid #1a3c58;
    border-radius: 8px;
    padding: 20px;
    
    .chart-header {
      margin-bottom: 15px;
      
      h4 {
        color: #75deef;
        font-size: 16px;
        margin: 0;
        display: flex;
        align-items: center;
        gap: 8px;
      }
    }
    
    .heatmap-container {
      .heatmap-content {
        width: 100%;
        min-height: 200px;
        overflow-x: auto;
      }
    }
  }
}

@media (max-width: 1200px) {
  .model-weight-category-chart {
    .chart-row {
      grid-template-columns: 1fr;
    }
  }
}
</style>